<template>
  <div class="module-detail-page">
    <div v-loading="loading" class="page-content">
      <!-- 返回按钮 -->
      <div class="page-actions">
        <el-button :icon="ArrowLeft" @click="goBack">返回列表</el-button>
      </div>

      <!-- 模块基本信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>模块基本信息</span>
            <el-button :icon="Edit" size="small" @click="editModule">编辑</el-button>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模块名称">
            {{ moduleData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="模块ID">
            {{ moduleData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="模块路径">
            {{ moduleData.path || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="模块类型">
            <el-tag :type="getModuleTypeColor(moduleData.name)">
              {{ getModuleType(moduleData.name) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatBytes(moduleData.size) }}
          </el-descriptions-item>
          <el-descriptions-item label="内存占用">
            {{ formatBytes(moduleData.pss) }}
          </el-descriptions-item>
          <el-descriptions-item label="引用进程">
            {{ moduleData.procesess || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" style="background-color: #e6f7ff;">
                <el-icon style="color: #409eff;" :size="24">
                  <Link />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ moduleData.deps || 0 }}</div>
                <div class="stat-label">依赖模块</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" style="background-color: #f0f9ff;">
                <el-icon style="color: #409eff;" :size="24">
                  <DataBoard />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ moduleData.dependedBy || 0 }}</div>
                <div class="stat-label">被依赖次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" style="background-color: #fff2e8;">
                <el-icon style="color: #e6a23c;" :size="24">
                  <Monitor />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getSymbolCount('total') }}</div>
                <div class="stat-label">符号总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" style="background-color: #f6ffed;">
                <el-icon style="color: #67c23a;" :size="24">
                  <Cpu />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ formatBytes(moduleData.swapPss || 0) }}</div>
                <div class="stat-label">Swap内存</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细信息标签页 -->
      <el-card class="detail-tabs" shadow="never">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <!-- 段信息 -->
          <el-tab-pane label="段信息" name="segments">
            <el-table
              :data="moduleData.segments || []"
              style="width: 100%"
              stripe
            >
              <el-table-column prop="name" label="段名称" />
              <el-table-column prop="vmaddr" label="虚拟地址" />
              <el-table-column prop="vmsize" label="虚拟大小">
                <template #default="{ row }">
                  {{ formatBytes(row.vmsize) }}
                </template>
              </el-table-column>
              <el-table-column prop="fileoff" label="文件偏移" />
              <el-table-column prop="filesize" label="文件大小">
                <template #default="{ row }">
                  {{ formatBytes(row.filesize) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 符号信息 -->
          <el-tab-pane label="符号信息" name="symbols">
            <div class="symbol-stats">
              <el-row :gutter="16">
                <el-col :span="6">
                  <el-statistic title="未定义符号" :value="getSymbolCount('undefined')" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="动态符号" :value="getSymbolCount('dynamic')" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="全局符号" :value="getSymbolCount('global')" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="局部符号" :value="getSymbolCount('local')" />
                </el-col>
              </el-row>
            </div>

            <el-table
              :data="symbolList"
              style="width: 100%"
              stripe
              max-height="400px"
            >
              <el-table-column prop="name" label="符号名称" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getSymbolTypeColor(row.type)" size="small">
                    {{ row.type }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="地址" />
              <el-table-column prop="size" label="大小" width="100">
                <template #default="{ row }">
                  {{ formatBytes(row.size) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 依赖关系 -->
          <el-tab-pane label="依赖关系" name="dependencies">
            <div class="dependencies-content">
              <div class="deps-filters">
                <el-radio-group v-model="dependencyType" @change="filterDependencies">
                  <el-radio-button label="direct">直接依赖</el-radio-button>
                  <el-radio-button label="indirect">间接依赖</el-radio-button>
                </el-radio-group>
              </div>

              <el-table
                :data="filteredDependencies"
                style="width: 100%"
                stripe
                max-height="400px"
              >
                <el-table-column prop="name" label="依赖模块" />
                <el-table-column prop="version" label="版本" />
                <el-table-column prop="type" label="依赖类型">
                  <template #default="{ row }">
                    <el-tag size="small">{{ row.type }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="count" label="引用次数" width="100" align="center" />
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 内存分析 -->
          <el-tab-pane label="内存分析" name="memory">
            <MemoryAnalysisChart :module-data="moduleData" />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Edit, Link, DataBoard, Monitor, Cpu } from '@element-plus/icons-vue'
import { useModulesStore } from '@/stores/modules'
import { formatBytes } from '@/utils/format'
import MemoryAnalysisChart from '@/components/charts/MemoryAnalysisChart.vue'

const router = useRouter()
const modulesStore = useModulesStore()

const loading = ref(true)
const moduleData = ref({})
const activeTab = ref('segments')
const dependencyType = ref('direct')

// 模拟符号列表
const symbolList = ref([
  { name: '_objc_load', type: 'undefined', address: '0x0000', size: 0 },
  { name: 'malloc', type: 'dynamic', address: '0x1000', size: 32 },
  { name: 'free', type: 'dynamic', address: '0x1020', size: 32 },
  { name: 'printf', type: 'global', address: '0x2000', size: 64 },
  { name: 'local_function', type: 'local', address: '0x3000', size: 128 }
])

// 模拟依赖关系
const dependencies = ref([
  { name: 'Foundation.framework', version: '1.0', type: 'dynamic', count: 10 },
  { name: 'UIKit.framework', version: '1.0', type: 'dynamic', count: 8 },
  { name: 'CoreFoundation', version: '1.0', type: 'dynamic', count: 15 },
  { name: 'libSystem.B.dylib', version: '1.0', type: 'dynamic', count: 25 }
])

const filteredDependencies = computed(() => {
  return dependencies.value.filter(dep =>
    dependencyType.value === 'direct' ? dep.count > 0 : true
  )
})

// 获取模块类型
const getModuleType = (name) => {
  try {
    if (!name) return '未知模块'
    if (name.includes('.dylib')) return '动态库'
    if (name.includes('.framework')) return '框架'
    if (name.includes('App')) return '应用'
    return '可执行文件'
  } catch (error) {
    console.warn('Error getting module type:', error)
    return '未知模块'
  }
}

const getModuleTypeColor = (name) => {
  try {
    const type = getModuleType(name)
    switch (type) {
      case '动态库': return 'info'
      case '框架': return 'warning'
      case '应用': return 'primary'
      case '未知模块': return 'warning'
      default: return 'success'
    }
  } catch (error) {
    return 'info'
  }
}

// 获取符号统计
const getSymbolCount = (type) => {
  try {
    if (!moduleData.value?.symbol_count) return 0
    return moduleData.value.symbol_count[type] || 0
  } catch (error) {
    return 0
  }
}

// 获取符号类型颜色
const getSymbolTypeColor = (type) => {
  try {
    switch (type) {
      case 'undefined': return 'danger'
      case 'dynamic': return 'warning'
      case 'global': return 'success'
      case 'local': return 'info'
      default: return 'info'
    }
  } catch (error) {
    return 'info'
  }
}

const goBack = () => {
  router.push('/modules')
}

const editModule = () => {
  // TODO: 实现模块编辑功能
}

const handleTabChange = (tabName) => {
  // 切换标签页时可能需要加载数据
  if (tabName === 'symbols' && symbolList.value.length === 0) {
    // 模拟加载更真实的符号数据
    symbolList.value = generateMockSymbols()
  }
}

// 生成模拟符号数据
const generateMockSymbols = () => {
  const symbolNames = [
    '_objc_load', '_objc_msgSend', 'malloc', 'free', 'printf', 'strlen', 'strcpy',
    'CFStringCreateWithCString', 'NSArray objectAtIndex', 'UIView initWithFrame',
    'UIApplicationMain', 'dispatch_async', 'dispatch_get_main_queue',
    'NSLog', 'NSLogv', 'assert', 'memcmp', 'memcpy', 'memset'
  ]

  const symbols = []

  // 添加常见系统符号
  symbolNames.forEach((name, index) => {
    symbols.push({
      name: name,
      type: index % 4 === 0 ? 'undefined' : index % 4 === 1 ? 'dynamic' : index % 4 === 2 ? 'global' : 'local',
      address: `0x${(index * 0x1000 + 0x100000000).toString(16).padStart(8, '0')}`,
      size: Math.floor(Math.random() * 128) + 16
    })
  })

  // 添加模块特定符号
  for (let i = symbolNames.length; i < 50; i++) {
    symbols.push({
      name: `${moduleData.value.name || 'Module'}_function_${i}`,
      type: ['local', 'global'][Math.floor(Math.random() * 2)],
      address: `0x${(i * 0x100 + 0x200000000).toString(16).padStart(8, '0')}`,
      size: Math.floor(Math.random() * 256) + 32
    })
  }

  return symbols
}

const filterDependencies = () => {
  // 依赖关系已在计算属性中处理
}

// 初始化模块数据
const initModuleData = async () => {
  const moduleId = router.currentRoute.value.params.id
  if (!moduleId) {
    loading.value = false
    return
  }

  try {
    // 首先尝试从已加载的模块列表中查找数据
    const existingModule = modulesStore.modules.find(m => m.id == moduleId)

    if (existingModule) {
      // 使用现有模块数据，并补充详细信息
      moduleData.value = {
        id: existingModule.id,
        name: existingModule.name,
        path: existingModule.path || '',
        size: existingModule.size || 0,
        pss: existingModule.memoryUsage || 0,
        deps: existingModule.dependencies || 0,
        dependedBy: Math.floor(Math.random() * 10), // 模拟被依赖数
        procesess: 'launchd, SpringBoard', // 模拟进程
        segments: generateMockSegments(),
        symbol_count: generateMockSymbolCount(),
        swapPss: Math.floor(Math.random() * 10000), // 模拟swap内存
        complexity: existingModule.complexity || 50
      }
    } else {
      // 尝试从API获取详细信息
      const data = await modulesStore.fetchModuleDetails(moduleId)

      if (data) {
        moduleData.value = {
          id: moduleId,
          name: data.name || 'Unknown Module',
          path: data.path || '',
          size: data.size || 0,
          pss: data.pss || 0,
          deps: data.deps || 0,
          dependedBy: data.dependedBy || 0,
          procesess: data.procesess || '',
          segments: data.segments || [],
          symbol_count: data.symbol_count || {},
          swapPss: data.swapPss || 0
        }
      } else {
        // 使用模拟数据
        moduleData.value = generateMockModuleData(moduleId)
      }
    }
  } catch (error) {
    // 使用模拟数据作为回退
    moduleData.value = generateMockModuleData(moduleId)
  } finally {
    loading.value = false
  }
}

// 生成模拟模块数据
const generateMockModuleData = (moduleId) => {
  const moduleNames = ['Foundation', 'UIKit', 'CoreFoundation', 'libSystem.B.dylib', 'libc++.1.dylib']
  const moduleName = moduleNames[moduleId % moduleNames.length] || `Module_${moduleId}`

  return {
    id: moduleId,
    name: moduleName,
    path: `/System/Library/Frameworks/${moduleName}`,
    size: Math.floor(Math.random() * 1000000) + 100000,
    pss: Math.floor(Math.random() * 50000) + 10000,
    deps: Math.floor(Math.random() * 50) + 5,
    dependedBy: Math.floor(Math.random() * 20) + 1,
    procesess: 'launchd, SpringBoard, Safari',
    segments: generateMockSegments(),
    symbol_count: generateMockSymbolCount(),
    swapPss: Math.floor(Math.random() * 10000),
    complexity: Math.floor(Math.random() * 80) + 20
  }
}

// 生成模拟段信息
const generateMockSegments = () => {
  return [
    { name: '__TEXT', vmaddr: '0x100000000', vmsize: 1048576, fileoff: 0, filesize: 1048576 },
    { name: '__DATA', vmaddr: '0x101000000', vmsize: 524288, fileoff: 1048576, filesize: 524288 },
    { name: '__LINKEDIT', vmaddr: '0x101080000', vmsize: 262144, fileoff: 1572864, filesize: 262144 }
  ]
}

// 生成模拟符号统计
const generateMockSymbolCount = () => {
  return {
    total: Math.floor(Math.random() * 1000) + 100,
    undefined: Math.floor(Math.random() * 50) + 10,
    dynamic: Math.floor(Math.random() * 200) + 50,
    global: Math.floor(Math.random() * 300) + 100,
    local: Math.floor(Math.random() * 500) + 200
  }
}

onMounted(() => {
  initModuleData()
})
</script>

<style scoped lang="scss">
.module-detail-page {
  .page-actions {
    margin-bottom: 20px;
  }

  .page-content {
    .info-card {
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 600;
      }
    }

    .stats-row {
      margin-bottom: 20px;

      .stat-card {
        .stat-content {
          display: flex;
          align-items: center;
          gap: 16px;

          .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .stat-info {
            .stat-value {
              font-size: 24px;
              font-weight: 700;
              color: var(--el-text-color-primary);
              line-height: 1;
            }

            .stat-label {
              font-size: 14px;
              color: var(--el-text-color-secondary);
              margin-top: 4px;
            }
          }
        }
      }
    }

    .detail-tabs {
      .symbol-stats {
        margin-bottom: 20px;
      }

      .deps-filters {
        margin-bottom: 16px;
      }

      .dependencies-content {
        height: 400px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .module-detail-page {
    .stats-row {
      .el-col {
        margin-bottom: 12px;
      }
    }

    .el-descriptions {
      :deep(.el-descriptions__cell) {
        display: block;
        width: 100% !important;
      }
    }
  }
}
</style>